package com.example.theadadmin.interceptor;

import com.example.theadadmin.util.JWTTokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JWTTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("request method:" + request.getMethod());
        String token = request.getHeader("Authorization");
        System.out.println("Token: " + token);
        // 判断有没有token , 拒绝用户访问
        if (StringUtils.isEmpty(token)) {
            response.setStatus(401);
            return false;
        }
        // 2. 解析token，如果解析报错，也说明token有问题
        token = token.replace("Bearer ", "");
        String subject = "";
        try {
            subject = JWTTokenUtil.parseToken(token);
        }catch (Exception e){
            response.setStatus(401);
            return false;
        }
        // 3. 数据库查询用户信息，如果查询不到，也说明token有问题
        System.out.println("Subject: " + subject);
        return true;

        // 4. 验证token是否有效，如果token过期，也说明token有问题

        // 5. 如果验证通过，则放行

    }
}
